#include "BaseFile.h"
#include <assert.h>
#ifdef _WIN32
#include <Windows.h>
#endif

int BaseFile::Read(int nOffset, int& nSize, unsigned char* pszBuf)
{
	if(m_pFile == NULL || pszBuf == NULL || nSize == 0)
		return -1;

	if(SeekTo((unsigned int)nOffset))
		return -1;

	return Read(nSize,pszBuf);
}

int BaseFile::Read(int& nSize, unsigned char* pszBuf)
{
	if(m_pFile == NULL || pszBuf == NULL)
		return -1;

	if(nSize <= 0 )
		return -1;

	int nReaded = 0;
	int nTmp    = 0;
	int nLen    = nSize;

	nSize = 0;

	for( int i = 0;!feof(m_pFile) &&  nReaded < nLen && i< 10;  i++)
	{
		nTmp = (int)fread(pszBuf+ nReaded,1,nLen - nReaded,m_pFile);

		if(ferror( m_pFile  ))
			break;

		nReaded += nTmp;
	}

	if(nReaded == nLen)
	{
		nSize = nLen;
		return 0;
	}
#ifdef _DEBUG

	unsigned int nErr= GetLastError();
	int  b = feof(m_pFile);
	int  a = ferror(m_pFile);
#endif
	nSize = nReaded;

	return -1;
}

int BaseFile::Write(int nSize,const unsigned char* pszBuf )
{
	if(m_pFile == NULL || pszBuf == NULL )
		return -1;

	if(nSize == 0 || nSize == -1)
		return 0;

	int  nWrited = 0;

	for(int i = 0;nWrited < nSize && i < 10; i++)
	{
		nWrited += (int)fwrite(pszBuf,1,nSize - nWrited,m_pFile);    
	}

	if( nWrited == nSize )
	{
		m_nSize += nWrited;
		fflush(m_pFile);
		return 0;
	}

	return -1;
}

int BaseFile::Write(int nOffset,int nSize,const unsigned char* pszBuf )
{
	if(m_pFile == NULL)
		return -1;

	if(SeekTo((unsigned int )nOffset))
		return -1;

	return Write(nSize,pszBuf);
}

BaseFile::BaseFile(const char* pszFileName)
{
	m_nSize = 0;
	InitFile(pszFileName);
}

BaseFile::BaseFile(FILE* pf)
{
	assert(pf);

	m_pFile = pf;

	rewind(m_pFile);

	fseek(m_pFile,0,SEEK_END);

	m_nSize = ftell(m_pFile);

	rewind(m_pFile);
}

BaseFile::~BaseFile()
{
	Close();
}

void BaseFile::Close()
{
	if(m_pFile)
		fclose(m_pFile);
}

int BaseFile::InitFile(const char* pszFileName)
{
	if(pszFileName == NULL)
		return -1;

	m_pFile = fopen(pszFileName,"r+b");

	if(m_pFile == NULL)
	{
		int nRet = ::GetLastError();
		m_pFile = fopen(pszFileName,"wb");
		m_nSize = 0;
		return -1;
	}

	rewind(m_pFile);

	fseek(m_pFile,0,SEEK_END);

	m_nSize = ftell(m_pFile);

	rewind(m_pFile);

	return 0;
} 

int   BaseFile::SeekTo(unsigned int nPos)
{
	if(m_pFile == NULL)
		return -1;

	if(nPos > m_nSize)
		return -1;

	rewind(m_pFile);

	return fseek(m_pFile,nPos,SEEK_CUR);
}

unsigned int BaseFile::GetCurPos()
{
	unsigned int n = ftell(m_pFile);
	return n;
}
